package client.comm.baoding.fragment

import android.content.Intent
import androidx.core.view.ViewCompat
import androidx.lifecycle.Observer
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.base.FinishReciver
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.StoreUtil
import client.comm.commlib.utils.Util

import client.comm.baoding.R
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.api.event.EventUserInfo
import client.comm.baoding.databinding.FragmentTabfourBinding
import client.comm.baoding.dialog.MsgTitleDialog
import client.comm.baoding.ui.*
import client.comm.baoding.ui.me.RealNameVerifyActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.baoding.utils.Constants
import client.comm.commlib.dialog.CameraOrSelectDialog
import client.comm.commlib.toast.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class TabFourFragment : BaseFragment<FragmentTabfourBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabfour
    }


    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initWidget() {
        EventBus.getDefault().register(this)

        binding.event = this
        binding.refreshLayout.setOnRefreshListener {
            viewModel.userInfo()
        }
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(R.color.main_color), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        viewModel.callUser.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    binding.userInfo = it.data

                    if (it.data!!.avatar != null) {
                        mImgLoader.load(it.data!!.avatar).error(R.mipmap.ic_launcher_round)
                            .into(binding.userAvatar)
                    } else {
                        binding.userAvatar.setImageResource(R.mipmap.ic_launcher_round)
                    }
                    binding.signBtn.text = if (it.data!!.r_status == 1) "已签到" else "签到"

                    if (it.data!!.r_status == 1) {
//                        binding.signBtn.isEnabled = false
                        binding.signBtn.setBackground(requireContext().getDrawable(R.drawable.comm_btn_selector_false))
                    }
                    binding.realname = when (it.data?.status) {
                        0 -> "实名认证 >"
                        1 -> "审核中"
                        else -> "已实名"
                    }

                }
                binding.refreshLayout.isRefreshing = false
            }
        })

        viewModel.rechargeOrder.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    it.data?.let {
                        if (it.recharge_list != null && it.recharge_list.size > 0) {
                            startActivity(Intent(context, RechargeOrderActivity::class.java))
                        } else {
                            startActivity(Intent(context, CreateRechargeActivity::class.java))
                        }
                    }
                    viewModel.rechargeOrder.value = null
                }
            }
        })

        viewModel.startCall.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    viewModel.isSign.value = true
                    binding.signBtn.text = "已签到"

                    viewModel.userInfo()
                } else {
                    viewModel.isSign.value = false
                }
            }
        })

        viewModel.sandPayRet.observe(this, Observer {
            it?.apply {
                if (isSuccess) {
//                    toast(it.message)//实名成功
//                    finish()
                    startActivity(Intent(requireActivity(), WebActivity::class.java).apply {
                        putExtra("adInfo", it.data?.sand_url)
                        putExtra("title", "我的钱包")
                    })
                } else {
                    toast(it.message)
                }
                viewModel.sandPayRet.value = null
            }
        })
    }

    override fun initData() {
        if (is_sw_btn) {
            binding.refreshLayout.apply {
                post(Runnable { isRefreshing = true })
            }
            is_sw_btn = false
        }

        viewModel.userInfo()
        showSysName()
    }

    var is_sw_btn: Boolean = false

    private fun showSysName() {
        binding.apply {
            if (SharedUtil.read(Constants.IS_ZEROHOST, "").isNullOrEmpty()) {
                tvSysName.text = "切换至子系统"
            } else {
                tvSysName.text = "切换至主系统"
            }

        }
    }

    /**
     * 切换主系统 /子系统，接口
     */
    fun switchPort() {
        is_sw_btn = true
        var sysNameDesc = binding.tvSysName.text
        MsgTitleDialog(requireContext()).apply {
            okTxt = "确定"
            cancleTxt = "取消"
            title = "确定$sysNameDesc?"
            ok = {

                if (!SharedUtil.read(Constants.IS_ZEROHOST, "").isNullOrEmpty()) {
                    SharedUtil.save(Constants.IS_ZEROHOST, "") //切换主系统
                } else {
                    SharedUtil.save(Constants.IS_ZEROHOST, "1") //切换子系统
                }
                initData()//刷新界面
            }
        }.show()
    }

    fun signIn(userInfo: UserInfo) {
        if (userInfo.r_status == 1) {
            return
        }
        MsgTitleDialog(requireContext()).apply {
            okTxt = "确定"
            cancleTxt = "取消"
            title = "确定签到?"
            ok = {
                viewModel.start()
            }
        }.show()
    }

    //用户信息修改成功时，回调刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun updateUserInfo(event: EventUserInfo?) {
        viewModel.userInfo()
    }

    fun imgSelect() {
        MsgTitleDialog(requireContext()).apply {
            okTxt = "去设置"
            cancleTxt = "取消"
            title = "设置用户头像？"
            ok = {
                CameraOrSelectDialog(requireActivity()).apply {
                    suc = {
                        viewModel.userAvatar.value = it
                        viewModel.setAvatar(requireActivity())
                    }
                }.show()
            }
        }.show()
    }

    fun meOrder(i: Int) {
        startActivity(Intent(context, GoodsOrderActivity::class.java).apply {
            putExtra("index", i)
        })
    }

    fun tuiOrder() {
        startActivity(Intent(context, TuikuanListActivity::class.java))
    }

    /**
     * 账号安全
     */
    fun accountSafe() {
        startActivity(Intent(context, AccountSafeActivity::class.java))

    }

    /**
     * 明细记录
     */
    fun zcjl(i: Int) {
        startActivity(Intent(context, MxJlActivity::class.java).apply {
            putExtra("index", i)
        })
    }

    fun myZc() {
        startActivity(Intent(context, MyZcActivity::class.java))
    }

    /**
     * 我的挂单
     */
    fun goZrMyGuaDan() {
        startActivity(Intent(context, MyGuaDan2Activity::class.java).apply {
            putExtra("goodsId", "") //it.goods_info.goods_id
        })
    }

    /**
     * 待释放记录
     */
    fun orderjl() {
//        startActivity(Intent(context, PendReleaseBalanceActivity::class.java))
//        startActivity(Intent(context, OrderJlActivity::class.java))
    }

    fun setskxx() {
        startActivity(Intent(context, SetSkxxActivity::class.java))
    }

    fun onKx() {
        startActivity(Intent(context, TxActivity::class.java))
    }

    fun onPdKx() {
        startActivity(Intent(context, PdTxActivity::class.java))
    }

    fun onApplyTx() {
        startActivity(Intent(context, ApplyTxActivity::class.java))
    }

    fun onBankKt() {
//        startActivity(Intent(context, BankTxActivity::class.java))
        startActivity(Intent(context, WdgpActivity::class.java))
    }

    fun onFej() {
//        startActivity(Intent(context, FejActivity::class.java))
    }

    fun storeIncome() {
        startActivity(Intent(context, StoreIncomeActivity::class.java))
    }


    /**
     * 修改用户名
     */
    fun resetUsername(username: String) {
        startActivity(Intent(context, UpdateUserInfoActivity::class.java).apply {
            putExtra("filed", username)
        })

    }

    /**
     * 转账
     */
    fun zz() {
        startActivity(Intent(context, Zz2Activity::class.java))

    }


    //提税/税费
    fun tishui() {
        startActivity(Intent(context, TiShuiActivity::class.java))

    }

    //积分
    fun jifen() {
//        startActivity(Intent(context, JifenActivity::class.java))

    }

    fun logout() {
        MsgTitleDialog(requireContext()).apply {
            title = "确认退出？"
            ok = {
                SharedUtil.clear("token")
                startActivity(Intent(context, LoginActivity::class.java))
                requireActivity().sendBroadcast(Intent(FinishReciver.FINISH_ACTION))
            }
            okTxt = "确认"
            cancleTxt = "取消"
        }.show()
    }

    fun about() {
        startActivity(Intent(context, AboutActivity::class.java))

    }

    //联系客服
    fun contactCustomer() {
        startActivity(Intent(context, ContactCustomerActivity::class.java))
    }

    fun setaddr() {
        startActivity(Intent(context, AddrMangerActivity::class.java))
    }

    fun setBank() {
        startActivity(Intent(context, BankManagerActivity::class.java))
    }

    fun walletDetail() {
        startActivity(Intent(context, QbyeActivity::class.java))
    }

    fun recharge() {
        viewModel.getRechargeOrder()
    }

    fun tuiguang() {
        startActivity(Intent(context, TuiGuangActivity::class.java))
    }


    fun coupon() {
        startActivity(Intent(context, MeCouponActivity::class.java))
    }

    fun couponList() {
        startActivity(Intent(context, AllCouponListActivity::class.java))
    }

    fun team() {
        startActivity(Intent(context, TdActivity::class.java).apply {
            putExtra("bean", StoreUtil.getBean<UserInfo>(requireContext())!!.id)
        })
    }

    fun daySign() {
        startActivity(Intent(context, DaySignActivity::class.java))
    }

    fun gyl() {
        startActivity(Intent(context, GylGoodsListActivity::class.java))
    }

    /**
     * 0 未实名
     * 1 审核中
     * 2 已审核
     */
    fun personInfo(status: Int) { // 判断是否实名认证 个人信息
        if (status == 0) {
            startActivity(Intent(context, RealNameVerifyActivity::class.java))
        } else {
            return
//            startActivity(Intent(context, PersonInfoActivity::class.java))
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    fun wdqb() {
        viewModel.sand_pay_account()
    }
}